<template>
  <div class="app-container">
    <van-nav-bar
      title="Todo List"
      fixed
      placeholder
    >
      <template #left v-if="currentUser">
        <span class="username">{{ currentUser.username }}</span>
      </template>
      <template #right>
        <template v-if="currentUser">
          <van-icon name="bars" size="18" @click="showActionSheet = true" />
        </template>
        <template v-else>
          <van-button size="small" type="primary" @click="showLoginForm = true">登录</van-button>
        </template>
      </template>
    </van-nav-bar>

    <div class="content">
      <!-- 未登录提示 -->
      <div v-if="!currentUser" class="login-prompt">
        <van-empty description="请先登录以使用待办事项功能">
          <template #bottom>
            <van-button type="primary" @click="showLoginForm = true">登录 / 注册</van-button>
          </template>
        </van-empty>
      </div>

      <!-- 已登录内容 -->
      <template v-else>
        <!-- Stats Summary -->
        <todo-stats :refresh-trigger="statRefreshTrigger" v-if="showStats" />

        <!-- Filters -->
        <todo-filter @filter-change="onFilterChange" />

        <!-- Todo List -->
        <div class="todo-list">
        <van-empty v-if="filteredTodos.length === 0" :description="emptyStateMessage" />

        <template v-else>
          <!-- Selection controls when in selection mode -->
          <div v-if="selectionMode" class="selection-controls">
            <van-button size="small" type="primary" @click="toggleSelectAll">
              {{ allSelected ? 'Deselect All' : 'Select All' }}
            </van-button>
            <div class="selection-actions">
              <van-button size="small" type="success" @click="batchComplete" :disabled="selectedTodos.length === 0">
                Complete
              </van-button>
              <van-button size="small" type="warning" @click="showPrioritySelector = true" :disabled="selectedTodos.length === 0">
                Set Priority
              </van-button>
              <van-button size="small" type="danger" @click="batchDelete" :disabled="selectedTodos.length === 0">
                Delete
              </van-button>
            </div>
          </div>

          <!-- Todo items -->
          <div class="todo-items">
            <template v-for="todo in filteredTodos" :key="todo.id">
              <div v-if="selectionMode" class="selectable-todo">
                <van-checkbox v-model="selectedIds[todo.id]" />
                <div class="todo-item-wrapper">
                  <todo-item :todo="todo" @todo-updated="onTodoUpdated" @edit-todo="editTodo" />
                </div>
              </div>
              <todo-item
                v-else
                :todo="todo"
                @todo-updated="onTodoUpdated"
                @edit-todo="editTodo"
              />
            </template>
          </div>
        </template>
        </div>

        <!-- Floating action button -->
        <div class="fab-button">
          <van-button
            round
            type="primary"
            size="normal"
            icon="plus"
            @click="showTodoForm = true"
          />
        </div>
      </template>
    </div>

    <!-- Todo Form Modal -->
    <todo-form
      v-model:visible="showTodoForm"
      :todo="currentTodo"
      @todo-added="onTodoAdded"
      @todo-updated="onTodoUpdated"
    />

    <!-- Login Form Modal -->
    <login-form
      v-model:visible="showLoginForm"
      @login-success="onLoginSuccess"
    />

    <!-- Action Sheet -->
    <van-action-sheet
      v-model:show="showActionSheet"
      title="Options"
      cancel-text="Cancel"
    >
      <div class="action-sheet-content">
        <van-cell title="Selection Mode" @click="toggleSelectionMode">
          <template #right-icon>
            <van-switch v-model="selectionMode" size="24" />
          </template>
        </van-cell>
        <van-cell title="Show Statistics" @click="toggleStats">
          <template #right-icon>
            <van-switch v-model="showStats" size="24" />
          </template>
        </van-cell>
        <van-cell title="Clear Completed" @click="clearCompleted" />
        <van-cell title="Clear All" @click="clearAll" />
        <van-cell title="退出登录" icon="cross" @click="logout" />
      </div>
    </van-action-sheet>

    <!-- Priority Selector for Batch Operations -->
    <van-action-sheet
      v-model:show="showPrioritySelector"
      title="Set Priority"
      cancel-text="Cancel"
    >
      <div class="priority-selector">
        <van-cell title="High Priority" clickable @click="batchSetPriority(1)">
          <template #right-icon>
            <div class="priority-indicator high"></div>
          </template>
        </van-cell>
        <van-cell title="Medium Priority" clickable @click="batchSetPriority(2)">
          <template #right-icon>
            <div class="priority-indicator medium"></div>
          </template>
        </van-cell>
        <van-cell title="Low Priority" clickable @click="batchSetPriority(3)">
          <template #right-icon>
            <div class="priority-indicator low"></div>
          </template>
        </van-cell>
      </div>
    </van-action-sheet>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted, watch } from 'vue';
import { showToast, showLoadingToast, closeToast, showDialog } from 'vant';
import axios from 'axios';
import { authApi, todoApi } from './api';
import TodoItem from './components/TodoItem.vue';
import TodoForm from './components/TodoForm.vue';
import TodoFilter from './components/TodoFilter.vue';
import TodoStats from './components/TodoStats.vue';
import LoginForm from './components/LoginForm.vue';

// State
const todos = ref([]);
const isLoading = ref(false);
const showTodoForm = ref(false);
const currentTodo = ref(null);
const showActionSheet = ref(false);
const selectionMode = ref(false);
const selectedIds = reactive({});
const showPrioritySelector = ref(false);
const showStats = ref(false);
const statRefreshTrigger = ref(0);
const currentUser = ref(null);
const showLoginForm = ref(false);

// Filter state
const filters = ref({
  search: '',
  status: 'all',
  priority: null,
  sortBy: 'priority',
  sortOrder: 'asc'
});

// Computed properties
const filteredTodos = computed(() => {
  let result = [...todos.value];

  // Apply search filter
  if (filters.value.search) {
    const searchLower = filters.value.search.toLowerCase();
    result = result.filter(todo =>
      todo.title.toLowerCase().includes(searchLower) ||
      (todo.description && todo.description.toLowerCase().includes(searchLower))
    );
  }

  // Apply status filter
  if (filters.value.status === 'completed') {
    result = result.filter(todo => todo.completed);
  } else if (filters.value.status === 'pending') {
    result = result.filter(todo => !todo.completed);
  }

  // Apply priority filter
  if (filters.value.priority !== null) {
    result = result.filter(todo => todo.priority === filters.value.priority);
  }

  // Apply sorting
  result.sort((a, b) => {
    let comparison = 0;

    if (filters.value.sortBy === 'priority') {
      comparison = a.priority - b.priority;
    } else if (filters.value.sortBy === 'due_date') {
      // Handle null due dates
      if (!a.due_date && !b.due_date) comparison = 0;
      else if (!a.due_date) comparison = 1;
      else if (!b.due_date) comparison = -1;
      else comparison = new Date(a.due_date) - new Date(b.due_date);
    } else if (filters.value.sortBy === 'created') {
      comparison = new Date(a.created_at) - new Date(b.created_at);
    }

    // Reverse for descending order
    return filters.value.sortOrder === 'desc' ? -comparison : comparison;
  });

  return result;
});

const selectedTodos = computed(() => {
  return Object.entries(selectedIds)
    .filter(([_, isSelected]) => isSelected)
    .map(([id]) => parseInt(id));
});

const allSelected = computed(() => {
  return filteredTodos.value.length > 0 &&
         filteredTodos.value.every(todo => selectedIds[todo.id]);
});

const emptyStateMessage = computed(() => {
  if (todos.value.length === 0) {
    return 'No todos yet';
  }
  if (filters.value.search || filters.value.status !== 'all' || filters.value.priority !== null) {
    return 'No todos match your filters';
  }
  return 'No todos found';
});

// 认证相关方法
const checkAuth = async () => {
  try {
    // 先从 localStorage 获取用户信息
    const storedUser = localStorage.getItem('currentUser');

    // 无论是否有本地存储，都先尝试从服务器验证用户
    try {
      const user = await authApi.getCurrentUser();
      if (user) {
        // 服务器验证成功，更新用户信息
        currentUser.value = user;
        localStorage.setItem('currentUser', JSON.stringify(user));
        fetchTodos();
      } else if (storedUser) {
        // 服务器验证失败，但有本地存储，清除本地存储
        localStorage.removeItem('currentUser');
        currentUser.value = null;
      }
    } catch (error) {
      console.error('Error validating user:', error);
      // 如果服务器验证出错，但有本地存储，仍然使用本地存储
      if (storedUser && !currentUser.value) {
        currentUser.value = JSON.parse(storedUser);
        // 尝试获取todos，如果失败会在fetchTodos中处理
        fetchTodos();
      }
    }
  } catch (error) {
    console.error('Error checking authentication:', error);
  }
};

const onLoginSuccess = (user) => {
  currentUser.value = user;
  // 将用户信息存储到 localStorage
  localStorage.setItem('currentUser', JSON.stringify(user));
  fetchTodos();
};

const logout = async () => {
  try {
    await authApi.logout();
    // 清除 localStorage 中的用户信息
    localStorage.removeItem('currentUser');
    currentUser.value = null;
    todos.value = [];
    showActionSheet.value = false;
    showToast('已退出登录');
  } catch (error) {
    console.error('Error logging out:', error);
    showToast('退出登录失败');
  }
};

// Todo相关方法
const fetchTodos = async () => {
  if (!currentUser.value) return;

  isLoading.value = true;
  try {
    // Build query parameters based on filters
    const params = {};
    if (filters.value.status === 'completed') params.completed = true;
    if (filters.value.status === 'pending') params.completed = false;
    if (filters.value.priority !== null) params.priority = filters.value.priority;
    if (filters.value.search) params.search = filters.value.search;
    params.sort_by = filters.value.sortBy;
    params.sort_order = filters.value.sortOrder;

    const data = await todoApi.getTodos(params);
    todos.value = data;
    // Reset selection when fetching new data
    if (selectionMode.value) {
      Object.keys(selectedIds).forEach(key => {
        selectedIds[key] = false;
      });
    }
  } catch (error) {
    if (error.response && error.response.status === 401) {
      currentUser.value = null;
      showToast('登录已过期，请重新登录');
    } else {
      showToast('加载待办事项失败');
      console.error('Error fetching todos:', error);
    }
  } finally {
    isLoading.value = false;
  }
};

const onTodoAdded = (todo) => {
  todos.value.unshift(todo);
  refreshStats();
};

const onTodoUpdated = (updatedTodo) => {
  if (updatedTodo.deleted) {
    todos.value = todos.value.filter(todo => todo.id !== updatedTodo.id);
  } else {
    const index = todos.value.findIndex(todo => todo.id === updatedTodo.id);
    if (index !== -1) {
      todos.value[index] = updatedTodo;
    }
  }
  refreshStats();
};

const editTodo = (todo) => {
  currentTodo.value = todo;
  showTodoForm.value = true;
};

const onFilterChange = (newFilters) => {
  filters.value = { ...filters.value, ...newFilters };
  fetchTodos();
};

const toggleSelectionMode = () => {
  selectionMode.value = !selectionMode.value;
  if (!selectionMode.value) {
    // Clear selections when exiting selection mode
    Object.keys(selectedIds).forEach(key => {
      selectedIds[key] = false;
    });
  }
};

const toggleSelectAll = () => {
  const newValue = !allSelected.value;
  filteredTodos.value.forEach(todo => {
    selectedIds[todo.id] = newValue;
  });
};

const batchDelete = () => {
  const selectedCount = selectedTodos.value.length;
  if (selectedCount === 0) return;

  showDialog({
    title: 'Delete Todos',
    message: `Are you sure you want to delete ${selectedCount} todos?`,
    showCancelButton: true,
  }).then(async () => {
    try {
      await todoApi.batchOperation('delete', selectedTodos.value);

      // Remove deleted todos from the list
      todos.value = todos.value.filter(todo => !selectedIds[todo.id]);
      showToast(`${selectedCount} todos deleted`);

      // Clear selections
      Object.keys(selectedIds).forEach(key => {
        selectedIds[key] = false;
      });

      refreshStats();
    } catch (error) {
      showToast('Failed to delete todos');
      console.error('Error deleting todos:', error);
    }
  });
};

const batchComplete = () => {
  const selectedCount = selectedTodos.value.length;
  if (selectedCount === 0) return;

  showDialog({
    title: 'Complete Todos',
    message: `Mark ${selectedCount} todos as completed?`,
    showCancelButton: true,
  }).then(async () => {
    try {
      await todoApi.batchOperation('complete', selectedTodos.value);

      // Update completed status in the local list
      todos.value.forEach(todo => {
        if (selectedIds[todo.id]) {
          todo.completed = true;
        }
      });

      showToast(`${selectedCount} todos marked as completed`);

      // Clear selections
      Object.keys(selectedIds).forEach(key => {
        selectedIds[key] = false;
      });

      refreshStats();
    } catch (error) {
      showToast('Failed to update todos');
      console.error('Error updating todos:', error);
    }
  });
};

const batchSetPriority = async (priority) => {
  const selectedCount = selectedTodos.value.length;
  if (selectedCount === 0) return;

  try {
    await todoApi.batchOperation('set_priority', selectedTodos.value, { priority });

    // Update priority in the local list
    todos.value.forEach(todo => {
      if (selectedIds[todo.id]) {
        todo.priority = priority;
      }
    });

    showToast(`Priority updated for ${selectedCount} todos`);

    // Clear selections
    Object.keys(selectedIds).forEach(key => {
      selectedIds[key] = false;
    });

    showPrioritySelector.value = false;
    refreshStats();
  } catch (error) {
    showToast('Failed to update priorities');
    console.error('Error updating priorities:', error);
  }
};

const clearCompleted = () => {
  showDialog({
    title: 'Clear Completed',
    message: 'Are you sure you want to delete all completed todos?',
    showCancelButton: true,
  }).then(async () => {
    try {
      // Get IDs of completed todos
      const completedIds = todos.value
        .filter(todo => todo.completed)
        .map(todo => todo.id);

      if (completedIds.length === 0) {
        showToast('No completed todos to clear');
        return;
      }

      await todoApi.batchOperation('delete', completedIds);

      // Remove completed todos from the list
      todos.value = todos.value.filter(todo => !todo.completed);
      showToast(`${completedIds.length} completed todos cleared`);
      refreshStats();
    } catch (error) {
      showToast('Failed to clear completed todos');
      console.error('Error clearing completed todos:', error);
    }
  });
};

const clearAll = () => {
  showDialog({
    title: 'Clear All',
    message: 'Are you sure you want to delete ALL todos? This cannot be undone!',
    showCancelButton: true,
  }).then(async () => {
    try {
      // Get all todo IDs
      const allIds = todos.value.map(todo => todo.id);

      if (allIds.length === 0) {
        showToast('No todos to clear');
        return;
      }

      await todoApi.batchOperation('delete', allIds);

      // Clear the list
      todos.value = [];
      showToast(`All todos cleared`);
      refreshStats();
    } catch (error) {
      showToast('Failed to clear todos');
      console.error('Error clearing todos:', error);
    }
  });
};

const toggleStats = () => {
  showStats.value = !showStats.value;
  if (showStats.value) {
    refreshStats();
  }
};

const refreshStats = () => {
  statRefreshTrigger.value++;
};

// Initialize
onMounted(() => {
  checkAuth();
});
</script>

<style>
.app-container {
  padding-bottom: 20px;
}

.content {
  padding: 16px;
  max-width: 600px;
  margin: 0 auto;
  padding-bottom: 80px; /* Space for FAB */
}

.todo-list {
  margin-top: 16px;
}

.fab-button {
  position: fixed;
  right: 16px;
  bottom: 16px;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  border-radius: 50%;
}

.action-sheet-content {
  padding: 16px 0;
}

.selection-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 0 8px;
}

.selection-actions {
  display: flex;
  gap: 8px;
}

.selectable-todo {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.todo-item-wrapper {
  flex: 1;
}

.priority-selector {
  padding: 16px 0;
}

.priority-indicator {
  width: 16px;
  height: 16px;
  border-radius: 50%;
}

.priority-indicator.high {
  background-color: #ee0a24;
}

.priority-indicator.medium {
  background-color: #ff976a;
}

.priority-indicator.low {
  background-color: #07c160;
}

.login-prompt {
  margin-top: 40px;
}

.username {
  font-weight: bold;
  font-size: 14px;
}
</style>
